<?php


namespace EasySwoole\EasySwoole;


use App\RenderDriver\TpTemplate;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\Template\Render as TemplateRender;

use EasySwoole\EasySwoole\ {
    Config,
    ServerManager,
    Swoole\EventRegister,
    AbstractInterface\Event,
};
use EasySwoole\Component\Di;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\Utility\Random;
use EasySwoole\Session\FileSession;
use EasySwoole\RedisPool\RedisPool;
use EasySwoole\Redis\Config\RedisConfig;

use EasySwoole\ORM\{Db\Result, DbManager, Db\Connection, Db\Config as DbConfig};
use App\Common\Session;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        date_default_timezone_set('Asia/Shanghai');
        // 注册连接池
        $dbconfig = Config::getInstance()->getConf('MYSQL');
        $config   = new DbConfig($dbconfig);
        DbManager::getInstance()->addConnection(new Connection($config));

        DbManager::getInstance()->onQuery(function (Result $ret, QueryBuilder $query) {
            Logger::getInstance()->log('sql:' . $query->getLastQuery());
        });

        $redisconfig = Config::getInstance()->getConf('REDIS');
        if ($redisconfig['cacheEnable'] && !RedisPool::getInstance()->getPool()) {
            RedisPool::getInstance()->register(new RedisConfig($redisconfig));
        }

        $sessionName = Config::getInstance()->getConf('SESSION.name');
        Session::getInstance(new FileSession(EASYSWOOLE_TEMP_DIR . '/Session'));
        Di::getInstance()->set(SysConst::HTTP_GLOBAL_ON_REQUEST, function (Request $request, Response $response) use ($sessionName) {
            $sessionId = $request->getCookieParams($sessionName);
            if (!$sessionId) {
                $sessionId = Random::character(32); // 生成 sessionId
                $response->setCookie($sessionName, $sessionId);
            }
            $request->withAttribute($sessionName, $sessionId);
            Session::getInstance()->create($sessionId);
        });

        Di::getInstance()->set(SysConst::HTTP_GLOBAL_AFTER_REQUEST, function (Request $request, Response $response) use ($sessionName) {
            Session::getInstance()->close($request->getAttribute($sessionName));

            Logger::getInstance()->log('----------------------start----------------------');
            Logger::getInstance()->log('url:' . $request->getUri()->getPath());
            Logger::getInstance()->log('----------------------end----------------------');
        });
    }

    public static function mainServerCreate(EventRegister $register)
    {
        // 注册模板渲染引擎服务
        $renderConfig = TemplateRender::getInstance()->getConfig();
        $renderConfig->setRender(new TpTemplate());
        $renderConfig->setTempDir(EASYSWOOLE_TEMP_DIR);
        TemplateRender::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());
    }
}
